#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <err.h>
#include <libmscommon/mscommon.h>
#include <libmscommon/msnetwork.h>
#include <libmscommon/msepoll.h>
#include <libmscommon/mstime.h>
#include <libmscommon/msmd.h>
#include <libmscommon/msenv.h>
#include <libmscommon/msmem.h>
#include <libmslog/mslog.h>
#include <libmsprotocol/msprotocol.h>

#define FLAG "PTC_CLENT"

#define mshostname_ipaddr	"192.168.200.244"
#define mshostname_port	50000
#define mshostname_url_http	"http://127.0.0.1:8010/ch31.ts"
#define mshostname_url_rtsp	"rtsp://127.0.0.1:8010/ch31.ts"

int main(int argc, char **argv)
{
	mslog_api_init( 53, ms_null,ms_null, ms_null);
	if(argc<2){
		ms_error("Userage:%s url" ,argv[0]);
		return 0;
	}
	msthread_api_envInit();
	msthread_api_setName("ptc_client");
	msmem_api_init(ms_false);
	msptc_api_init();
	msptc_api_register();
	msmd_api_setUlimit();
	
	ms_debug("Get param");
	mslog_api_init( 53, "/home/sugao","client.log", ms_null);

	URLContext cilent_ctt;
	URLContext *pcilent_ctt=&cilent_ctt;
	ms_memset0(pcilent_ctt, sizeof(URLContext));
	ms_strcpy(pcilent_ctt->url,(argv[1]));
//Get msptl_in	
	msptc_api_urlSplit_urlctt(pcilent_ctt);
	URLProtocol *msptl_in=msptc_api_matchByName(pcilent_ctt->url_info.ptcName);
	ms_debug("url_open");
	if(ms_strncmp_saeq(msptl_in->name, PTLNAME_WEBSOCKECT)){
		pcilent_ctt->opt.ws.dataType=WDT_TXTDATA;
	}
	if(msptl_in->url_open(pcilent_ctt)<0){
		ms_errGoto(ms_end, "open %s failed",pcilent_ctt->url);
	}

	ms_sleep(1);
	ms_debug("url_write");
	ms_byte *sendstr="Hello,I am client";
	ms_s32 len_need_send=ms_buflen(sendstr);
	ms_s32 len_send=msptl_in->url_write(pcilent_ctt,sendstr,len_need_send);
	if(len_send>0){
		ms_verbose("test:Send success!(len_send,len_need_send:%d,%d)-Context:%s%s ",len_send,len_need_send,LINE_END,sendstr);
		if(ms_strncmp_saeq(msptl_in->name, PTLNAME_WEBSOCKECT)){
			ms_verbose("dataType:%d ",pcilent_ctt->opt.ws.dataType);
		}
	}else{
		ms_error("test:Send failed!(len_send,len_need_send:%d,%d)-Context:%s%s ",len_send,len_need_send,LINE_END,sendstr);
	}

	ms_sleep(1);
	ms_byte recvbuf[1024]={0};
	ms_debug("url_read");
	ms_s32 len=msptl_in->url_read(pcilent_ctt,recvbuf,ms_bufsize(recvbuf));
	if(len>0){
		ms_verbose("test:Read success!Context:%s%s", LINE_END,recvbuf);
		if(ms_strncmp_saeq(msptl_in->name, PTLNAME_WEBSOCKECT)){
			ms_verbose("dataType:%d ",pcilent_ctt->opt.ws.dataType);
		}
	}else{
		ms_error("test:Read failed!");
	}
	msptl_in->url_close(pcilent_ctt);
ms_end:	
	msthread_api_envDeinit();
	msptc_api_deinit();
	msmem_api_deinit();
	mslog_api_deinit();
}
#undef MAIN_C

